
define(function(require, exports, module) {
    "use strict";

    var result = {};

    var METHOD = require("./method"),
        CONFIG = require("./config");

    // 输入框 校验
    Vue.directive('inputnumber', {
        bind: function (flag) {
            $(this.el).on("keyup", function(e){
                var position = this.selectionStart;
                if (e.keyCode == 37 || e.keyCode == 39) return;
                var r = this.value.replace(/[^\d]/g, "");
                this.value = r;
                this.selectionEnd = position;
            });
        }
    });

    // 手机号码 输入框 校验
    Vue.directive('inputphone', {
        bind: function (flag) {
            $(this.el).on("keyup", function(){
                var r = this.value.replace(/[^\d]/g, "");
                r = r.replace(/^[^1]\d*/g, "");
                this.value = r;
                this.selectionEnd = position;
            });
        }
    });

    Vue.directive('inputnumberdot', {
        bind: function (flag) {
            $(this.el).on("keyup", function(e){
                if (e.keyCode == 37 || e.keyCode == 39) return;
                var r = this.value;
                r = r.replace(/[^\d.]/g,"");  //清除“数字”和“.”以外的字符
                r = r.replace(/^\./g,"");  //验证第一个字符是数字而不是.
                r = r.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的.
                r = r.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
                r = r.replace(/(\.\d\d)\d+/g, "$1");
                this.value = r;
                this.selectionEnd = position;
            });
        }
    });
    Vue.filter('empty', function(s){
        if (s && s.length) {
            return s;
        } else {
            return '--';
        }
    });

    // 处理金钱
    Vue.filter('markMoney', function(s){
        if (s === "- -") return s;
        var n = 2, f = false;
        if (s < 0) {
            f = true;
            s = -s;
        }
        s = parseFloat((s + "").replace(/[^\d\.]/g, "")).toFixed(n) + "";
        var l = s.split(".")[0].split("").reverse(), r = s.split(".")[1];
        var t = "", i;
        for (i = 0; i < l.length; i++) {
            t += l[i] + ( (i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
        }
        return (f ? '-' : '') + t.split("").reverse().join("") + "." + r;
    });

    // 申购方式
    Vue.filter('applyType', function(v) {
        var s = ['市值','抢单','抢单 + 市值'],
            index = parseFloat(v) - 1;

        return s[index];
    });

    // 藏品状态
    Vue.filter('collectStatus', function(v) {
        var s = {
            "1"  : '待审核',
            "2"  : '申购中',
            "3"  : '待上市',
            "4"  : '上市中',
            "5"  : '临时停牌',
            "6"  : '停牌中',
            "7"  : '已退市',
            "8"  : '审核通过',
            "9"  : '审核失败',
            "10" : '待申购'
        };

        return s[v];
    });

    // 提货状态
    Vue.filter('takenStatus', function(v) {
        var s = {
            "1"  : '未审核',
            "2"  : '已通过',
            "3"  : '已驳回',
            "4"  : '已办理',
            "5"  : '已过期'
        };

        return s[v];
    });

    // 出金黑名单状态
    Vue.filter('wbType', function(v) {
        var s = {
            '1' : '添加',
            '2' : '修改',
            '3' : '删除'
        };

        return s[v];
    });

    // 停牌状态
    Vue.filter('pauseStatus', function(v) {
        var s = {
            "1"  : '待审核',
            "2"  : '待停牌',
            "3"  : '已拒绝',
            "4"  : '停牌中',
            "5"  : '已复牌',
            "6"  : '已过期'
        };

        return s[v];
    });

    // 持仓转让详情状态
    Vue.filter('tranStatus', function(v) {
        var s = {
            "0"  : '已取消',
            "1"  : '待处理',
            "2"  : '处理中',
            "3"  : '已成功',
            "4"  : '已失败'
        };

        return s[v];
    });

    // 申购详情状态
    Vue.filter('applyStatus', function(v) {
        var s = {
            "0"  : '已取消',
            "1"  : '待处理',
            "2"  : '申购成功',
            "3"  : '申购失败',
            "4"  : '进行中',
            "5"  : '已拒绝'
        };

        return s[v];
    });

    // 资金变动类型
    Vue.filter('changeType', function(v) {
        var s = {
            "1"  : '入金',
            "2"  : '交易卖出',
            "3"  : '转让卖出',
            "4"  : '申购卖出',
            "5"  : '佣金返还',
            "6"  : '出金',
            "7"  : '交易买入',
            "8"  : '转让买入',
            "9"  : '申购买入',
            "10" : '买入手续费',
            "11" : '卖出手续费',
            "12" : '转入手续费',
            "13" : '转出手续费',
            "14" : '申购手续费',
        };

        return s[v] ? s[v] : v;
    });

    // 委托状态
    Vue.filter('entrustState', function(v) {
        var s = {
            "0"  : '全部撤单',
            "1"  : '未成交',
            "2"  : '部分撤单',
            "3"  : '部分成交',
            "4"  : '全部成交',
        };

        return s[v];
    });

    // 锁仓状态
    Vue.filter('lockStatus', function(v) {
        var s = {
            "1"  : '待执行',
            "2"  : '已成功',
            "3"  : '已失败',
            "4"  : '已取消'
        };

        return s[v];
    });

    // 角色类型
    Vue.filter('adminType', function(v) {
        var s = {
            "1"  : '添加',
            "2"  : '启用',
            "3"  : '禁用',
            "4"  : '重置密码'
        };

        return s[v];
    });



    var Pikaday = require("../plugins/pikaday/pikaday");
    var i18n = { // 本地化
        previousMonth   : '上个月',
        nextMonth       : '下个月',
        months          : ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'],
        weekdays        : ['周日','周一','周二','周三','周四','周五','周六'],
        weekdaysShort   : ['日','一','二','三','四','五','六']
    }
    Vue.directive('time', {
        bind : function(){
            var me = this;
            new Pikaday({
                field: me.el,
                i18n: i18n,
                // minDate: new Date(),
                onSelect: function() {
                    var v = METHOD.changeTime(this._d, "yyyy-mm-dd");
                    me.el.value = v;
                    // $(me.el).addClass('nobg');
                    // me.set(v);
                }
            });
        },
        update : function(c){
            // var me = this;
            // me.el.value = c || "";
        }
    });


    // 头部导航
    var zt_header = require("text!../../html/tpl/headers.tpl");
    Vue.component('headers', {
        template: zt_header,
        props: ['userobj'],
        data: function(){
            return {
                userobj : null
            }
        },
        init: function(){
            var me = this;

            METHOD.ajax("admin/get_login_user").done(function(json){
                me.userobj = json.data;
            });
        },
        methods: {
            loginout : function (){
                METHOD.loading.show();
                METHOD.ajax("admin/logout").done(function(json){
                    METHOD.loading.hide();
                    window.location.href = "../login.html";
                }).fail(function(){
                    METHOD.loading.hide();
                    window.location.href = "../login.html";
                });
            }
        }
    });

    // 左导航
    var zt_nav = require("text!../../html/tpl/nav.tpl");
    Vue.component('menunav', {
        template: zt_nav,
        props: ['index','sub','navobj'],
        init: function() {},
        data : function() {
            var mtog = CONFIG.session.get('menuTog') ? true : false;

            return {
                tog : mtog
            }
        },
        methods: {
            clickTit : function(t){
                if (this.index && this.index == t) {
                    this.index = null;
                } else {
                    this.index = t;
                }
            },
            toggle : function(){
                var me = this;
                me.tog = !me.tog;
                if (me.tog) {
                    CONFIG.session.set('menuTog', 1);
                } else {
                    CONFIG.session.remove('menuTog');
                }
            }
        }
    });


    // 分页
    var tm_page = require("text!../../html/tpl/pages.tpl");

    Vue.component('pages', {
        template: tm_page,
        props: ['cur', 'all'],
        data: function(){},
        computed: {
            indexs: function(){
              var left = 1;
              var right = this.all;
              var ar = [];
              if(this.all>= 11){
                if(this.cur > 5 && this.cur < this.all-4){
                        left = this.cur - 5;
                        right = this.cur + 4;
                }else{
                    if(this.cur<=5){
                        left = 1;
                        right = 10;
                    }else{
                        right = this.all;
                        left = this.all -9;
                    }
                }
             }
            while (left <= right){
                ar.push(left);
                left ++;
            }
            return ar;
           }
        },
        methods: {
            btnClick: function(data){
                // if(data != this.cur) {// }
                this.cur = data;
                this.$dispatch('btn-click', data);
            }
        }
    });


    // 检测所有输入的数据格式，以及显示警告
    var patternObj = {
        "require": {
            regexp: /.+/,
            tip: "不能为空",
        },
        "int":{
            regexp:/^[0-9]*$/,
            tip: "须为整数"
        },
        "decimal":{
            regexp: /^\d*(\d?\.[\d])?$/,
            tip: "须为数字,且只能保留一位小数"
        },
        "float":{
            regexp: /^\d*(\d?\.\d{1,2})?$/,
            tip: "须为数字,且只能保留两位小数"
        },
        "length" : {
            tip : "长度值必须为", // 后面补上
        },
        "max" : {
            tip : "最大值不能超过", // 后面补上
        },
        "min" : {
            tip : "最小值不能小于", // 后面补上
        },
        "complex":{
            regexp: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$/,
            tip: "请填写8-16位数字与字母的组合密码"
        },
        "phone":{
            regexp: /^1[0-9]{10}$/,
            tip: "请输入正确的手机号"
        },
        "url":{
            regexp: /^(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?$/,
            tip: "请输入正确的网址"
        },
        "email": {
            regexp: /^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/,
            tip: "请输入正确的邮箱"
        },
        "idcard": {
            regexp: /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/,
            tip: "请填写正确的身份证"
        }
    }

    Vue.directive('allcheck', {
        twoWay: true,
        update: function (obj) {
            var me = this,
                $el = $(this.el).find("[check]"),
                $tip = $("<span class='m_line_tip error' style='display:none'></span>");

            $el.on("input", function(){
                checkInput($(this));
            });

            obj.$valid = function(){
                var $newEl = $(me.el).find("[check]");
                $el = $newEl;
                $el.next().remove();
                $el.after($tip);
                var flagObj = null;
                $el.each(function(i, sel){
                    var r = checkInput($(sel));
                    if (flagObj) return;
                    if (!r.flag) {
                        flagObj = r;
                    }
                });
                obj.flag = flagObj ? flagObj.flag : true;
                obj.tip = flagObj ? flagObj.tip : "";
                me.set(obj);
            };
            var checkInput = function($input){
                // show 为控制校验时不校验非必填项
                var $error = $input.next(),
                    r = check($input.val(), $input.attr("check"));
                $error.html(r.tip);
                if (!r.flag) {
                    $error.show();
                } else {
                    $error.hide();
                }
                return r;
            }
            var check = function(val, str){
                str = str.replace(/'/g, "\"");
                // console.log(str);
                var gui = JSON.parse(str),
                      r = {flag: true, tip: ""},
                      j = 0, lb, equal, v, pv, type;
                lb = gui.length;
                for (; j < lb; j++) {
                    if (!r.flag) break;
                    v = gui[j];
                    type = v.type;
                    pv = patternObj[type];
                    if( pv ){
                        // 正则匹配
                        if (pv.regexp) {
                            if( type !== "require" && val !== "" && !pv.regexp.test(val) ){
                                r.flag = false;
                                r.tip = !v.tip ? pv.tip : v.tip;
                            } else if( type === "require" && !pv.regexp.test(val)) {
                                r.flag = false;
                                r.tip = !v.tip ? pv.tip : v.tip;
                            } else {
                                r.flag = true;
                                r.tip = !v.tip ? pv.tip : v.tip;
                            }
                        } else if (type === "max") {
                            if (val > v.val) {
                                r.flag = false;
                                r.tip = !v.tip ? (pv.tip + v.val) : v.tip;
                            }
                        } else if (type === "min") {
                            equal = v.equal || 0;
                            if(equal && val <= v.val ) {
                                r.flag = false;
                                r.tip = !v.tip ? (pv.tip + v.val) : v.tip;
                            } else if (val < v.val) {
                                r.flag = false;
                                r.tip = !v.tip ? (pv.tip + v.val) : v.tip;
                            }
                        } else if (type === "length") {
                            if (v.val && val.length !== v.val) {
                                r.flag = false;
                                r.tip = !v.tip ? (pv.tip + "等于" + v.val + "位") : v.tip;
                            } else if (v.min && val.length < v.min) {
                                r.flag = false;
                                r.tip = !v.tip ? (pv.tip + "大于等于" + v.min + "位") : v.tip;
                            } else if (v.max && val.length > v.max) {
                                r.flag = false;
                                r.tip = !v.tip ? (pv.tip + "小于等于" + v.max + "位") : v.tip;
                            }
                        }
                    }
                }
                return r;
            }

        }
    });

    // 产品选择框
    var changAjax;
    Vue.component('productselect', {
        template: "<select class='m_select m_medium' v-model='col_id'>" +
                    "<option value='' hidden v-if='name'>{{ name }}</option>" +
                    "<option v-if='all' value=''>{{ all }}</option>" +
                    "<option value='{{ item.col_id }}' v-for='item in list'>{{ item.name }}</option>"+
                    "</select>",
        props: ["col_id", "name", "all", "status", "url"],
        data: function(){
            return {
                list : [],
                tip: ""
            }
        },
        init: function(){
            var me = this;
            setTimeout(function() {
                var url = me.url || "collection/list_issued?page=1&num=100";
                if (!changAjax) {
                    changAjax = METHOD.ajax(url);
                }

                changAjax.done(function(json) {
                    setTimeout(function() {
                        if (me.status) {
                            me.list = json.data.filter(function(v){
                                return v.status == me.status;
                            });
                        } else {
                            me.list = json.data;
                        }
                    }, 100);
                });
            }, 10);
        },
        methods: {
        }
    });

    // 管理员 / 添加人 / 操作人 选择框
    var adminAjax;
    Vue.component('adminselect', {
        template: "<select class='m_select' v-model='admin_id'><option value='' hidden v-if='name'>{{ name }}</option><option v-if='all' value=''>{{ all }}</option><option value='{{ item.id }}' v-for='item in list'>{{ item.user_name }}</option></select>",
        props: ["admin_id","name", "all"],
        data: function(){
            return {list : []}
        },
        init: function(){
            var me = this;
            if (!adminAjax) {
                adminAjax = METHOD.ajax("admin/all_list")
            }
            adminAjax.done(function(json) {
                setTimeout(function() {
                    me.list = json.data;
                }, 100);
            });
        },
        methods: {
        }
    });


    // 交易号联动
    Vue.directive('nogetinfo', {
        bind : function(){

        },
        update : function(c){
            // console.log(c)
            var index;

            if (c.hasOwnProperty("cb")){
                index = c.cb.toString();
            }

            if (c.val.length == 12) {
                METHOD.ajax("user/info/no", { no: c.val }).done(function(json){
                    index ? c.fn(json.data,index) : c.fn(json.data);
                }).fail(function(){
                    index ? c.fn(null,index) : c.fn(null);
                });
            } else {
                index ? c.fn(null,index) : c.fn(null);
            }
        }
    });

    module.exports = Vue;

});

